#pragma once

#include "Comm.hpp"
#include "Nocopy.hpp"
#include "Log.hpp"
#include "LockGuard.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <string>
#include <errno.h>
#include <functional>
#include <pthread.h>

const static int defaultfd = -1;
const static uint16_t defaultport = 8888;
const static int defaultsize = 1024;
 
using task_t = function<void(void)>;

// 服务器的IP不应该是固定的，而是任意的
class UdpServer : public Nocopy
{
public:
    UdpServer(uint16_t port = defaultport)
        :_port(port),_sockfd(defaultfd)
    {
    }

    void Init()
    {
        // 创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg.LogMessage(Fatal, "create socket fail\n");
            exit(Socket_err);
        }
        lg.LogMessage(Info, "create socket success , sockfd : %d\n", _sockfd);

        // 2、绑定，指定网络信息，协议家族，IP地址，端口号，结构体填充，设置到内核
        struct sockaddr_in ServerSockaddr;
        memset(&ServerSockaddr,0,sizeof(ServerSockaddr));
        ServerSockaddr.sin_family = AF_INET;
        ServerSockaddr.sin_port = htons(_port);
        ServerSockaddr.sin_addr.s_addr = INADDR_ANY; // 就是0
        socklen_t len = sizeof(ServerSockaddr);
        
        int n = ::bind(_sockfd, (struct sockaddr*)&ServerSockaddr, len);
        if (n == -1)
        {
            // cout << inet_ntoa(ServerSockaddr.sin_addr) << ":" << ntohs(ServerSockaddr.sin_port) << endl;
            lg.LogMessage(Fatal, "bind fail , errno : %d , %s\n", errno , strerror(errno));
            exit(Bind_err);
        }
        lg.LogMessage(Info, "bind success , sockfd : %d\n", _sockfd);

        pthread_mutex_init(&_mutex,nullptr);
        ThreadPool<task_t>::GetInstance()->Start();
    }

    void AddOnlineUser(InetAddr addr)
    {
        LockGuard lock(&_mutex);
        for(auto tmp : _online_user)
        {
            if(tmp == addr)
                return;
        }
        _online_user.push_back(addr);
    }

    void Route(int sockfd ,const string& message)
    {
        LockGuard lock(&_mutex);
        for(auto &tmp : _online_user)
        {
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&tmp.GetAddr(), sizeof(tmp));
        }
    }

    void Start()
    {
        char inbuffer[defaultsize];
        for (;;)
        {
            struct sockaddr_in ClientSockaddr;
            socklen_t ClientLen = sizeof(ClientSockaddr);

            // 接收数据
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&ClientSockaddr, &ClientLen);
            if (n > 0)
            {
                inbuffer[n] = 0;

                InetAddr inetaddr(ClientSockaddr);
                AddOnlineUser(inetaddr);
                cout << inetaddr.PrintDebug() << inbuffer<< endl;

                string message = inbuffer;
                task_t task = bind(&UdpServer::Route,this,_sockfd,message);

                ThreadPool<task_t>::GetInstance()->Push(task);
            }
        }
    }

    ~UdpServer()
    {
        pthread_mutex_destroy(&_mutex);
        close(_sockfd);
    }

private:
    // std::string _ip;
    uint16_t _port;
    int _sockfd;
    vector<InetAddr> _online_user;

    pthread_mutex_t _mutex;
};